﻿using GameFramework;
using GameFramework.Procedure;
using GameFramework.Fsm;
using GameFramework.Event;
using UnityGameFramework.Runtime;

namespace MYSTARFORCE {
    public class ProcedureMenu : ProcedureBase
    {
        public bool IsStartGame = false;

        private MenuForm m_MenuForm = null;

        // 进入流程
        protected override void OnEnter(IFsm<IProcedureManager> procedureOwner)
        {
            base.OnEnter(procedureOwner);

            // 订阅打开界面成功的事件
            GameEntry.Event.Subscribe(OpenUIFormSuccessEventArgs.EventId, OnOpenUIFormSuccess);

            IsStartGame = false;

            GameEntry.UI.OpenUIForm(UIFormId.MenuForm,this);
        }

        // 离开流程
        protected override void OnLeave(IFsm<IProcedureManager> procedureOwner, bool isShutdown)
        {
            base.OnLeave(procedureOwner, isShutdown);

            // 取消订阅的事件
            GameEntry.Event.Unsubscribe(OpenUIFormSuccessEventArgs.EventId, OnOpenUIFormSuccess);

            // 如果界面存在，就关闭界面，同时把成员变量清空
            if(m_MenuForm != null)
            {
                m_MenuForm.Close(isShutdown);
                m_MenuForm = null;
            }
        }

        // 刷新流程
        protected override void OnUpdate(IFsm<IProcedureManager> procedureOwner, float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(procedureOwner, elapseSeconds, realElapseSeconds);

            if (IsStartGame)
            {
                procedureOwner.SetData<VarInt>(Constant.ProcedureData.NextSceneId, GameEntry.Config.GetInt("Scene.Main"));
                //TODO: 原版游戏会进入生存模式，但游戏有且只有一个模式，因此留待以后酌情添加
                ChangeState<ProcedureChangeScene>(procedureOwner);
            }
        }

        // 成功打开界面时
        private void OnOpenUIFormSuccess(object sender, GameEventArgs e)
        {
            OpenUIFormSuccessEventArgs ne = (OpenUIFormSuccessEventArgs)e;
            if(ne.UserData != this)
            {
                return;
            }
            m_MenuForm = (MenuForm)ne.UIForm.Logic;
        }
    }
}